package CSV;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;

public class ProcessRawData {

	HashMap<String, HashSet<String>> transactions;
	String csvpath;
	String outputpath;

	public ProcessRawData(String csvpath, String output) {

		this.csvpath = csvpath;
		this.outputpath = output;
		this.transactions = new HashMap<String, HashSet<String>>();
		this.ReadinFile();
		this.WriteFile();
	}

	private void ReadinFile() {
		// change the .csv file to the file we want

		FileReader read;
		BufferedReader br;

		String content = "";
		try {
			read = new FileReader(this.csvpath);
			br = new BufferedReader(read);
			while ((content = br.readLine()) != null) {
				String[] attrs = content.split(",");
				String idx_col = "";
				String list_col = "";
				for (int i = 0; i < attrs.length; i++) {
					switch (i) {
					case 1:
						idx_col  = idx_col + attrs[i];
						break;
					case 0:
						list_col = list_col + attrs[i];
						break;
					default:
					}
				}
				if (this.transactions.containsKey(idx_col)) {
					HashSet<String> temp_hs = this.transactions.get(idx_col);
					temp_hs.add(list_col);
				} else {
					HashSet<String> temp_hs = new HashSet<String>();
					temp_hs.add(list_col);
					this.transactions.put(idx_col, temp_hs);
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void WriteFile() {
		FileWriter fw;
		BufferedWriter bf = null;
		try {
			fw = new FileWriter(this.outputpath);
			bf = new BufferedWriter(fw);
		} catch (IOException e) {
			e.printStackTrace();
		}

		Iterator<String> iter = this.transactions.keySet().iterator();
		while (iter.hasNext()) {
			String places = iter.next();
			HashSet<String> complain = this.transactions.get(places);
			//System.out.println(places);
			try {
				if (places.length()>0)
				bf.write(places+"|||");
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			Iterator<String> topics = complain.iterator();
			while (topics.hasNext()) {
				String onetopic = topics.next();
				try {
					if (!onetopic.equals("")) {
						bf.write(onetopic);
						//System.out.println(onetopic.toString());
						if (topics.hasNext())
							bf.write(",");
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			try {
				if (iter.hasNext())
					bf.write("\n");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		try {
			bf.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
